import random
from datetime import datetime
from utils.file_handler import FileHandler

class Teacher:
    def __init__(self):
        self.operations = ['+', '-', '*', '/']
        self.file_handler = FileHandler()
    
    def generate_exam(self, exam_id, question_count=5):
        """生成试卷"""
        exam = {
            'exam_id': exam_id,
            'questions': [],
            'answers': [],
            'create_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        for i in range(question_count):
            question, answer = self._generate_question(i + 1)
            exam['questions'].append(question)
            exam['answers'].append(answer)
        
        self.file_handler.save_exam(exam)
        return exam_id
    
    def _generate_question(self, index):
        """生成随机数学题"""
        operation = random.choice(self.operations)
        
        if operation in ['+', '-']:
            # 加减法控制在100以内
            num1 = random.randint(0, 100)
            num2 = random.randint(0, 100)
            if operation == '-':
                # 确保减法结果为正数
                num1, num2 = max(num1, num2), min(num1, num2)
        else:
            # 乘除法控制在200以内
            if operation == '*':
                num1 = random.randint(0, 20)
                num2 = random.randint(0, 10)
            else:  # 除法
                num2 = random.randint(1, 10)  # 除数不能为0
                # 确保除法没有余数
                num1 = num2 * random.randint(1, 20)
            
        # 格式化题目，保持对齐
        question = f"第{index:02d}题: {num1:3d} {operation} {num2:3d} = "
        correct_answer = eval(f"{num1} {operation} {num2}")
        return question, correct_answer
    
    def format_exam_questions(self, questions):
        """格式化试卷显示"""
        formatted = "\n试卷内容：\n" + "="*60 + "\n\n"
        for i in range(0, len(questions), 4):  # 每4题一行
            row = questions[i:i+4]
            formatted += "    ".join(row) + "\n\n"
        formatted += "="*60
        return formatted
    
    def grade_submission(self, submission_id):
        """批改答卷"""
        submission = self.file_handler.load_submission(submission_id)
        exam = self.file_handler.load_exam(submission['exam_id'])
        
        total_questions = len(exam['questions'])
        score = 0
        wrong_questions = []
        results = []
        
        for i, (student_ans, correct_ans, question) in enumerate(
            zip(submission['answers'], exam['answers'], exam['questions'])):
            try:
                is_correct = float(student_ans) == float(correct_ans)
                if is_correct:
                    score += 1
                else:
                    wrong_questions.append({
                        'question': question,
                        'student_answer': student_ans,
                        'correct_answer': correct_ans
                    })
                results.append(is_correct)
            except:
                results.append(False)
                wrong_questions.append({
                    'question': question,
                    'student_answer': student_ans,
                    'correct_answer': correct_ans
                })
        
        # 计算百分制分数
        final_score = round((score / total_questions) * 100)
        
        # 更新提交信息
        submission['score'] = final_score
        submission['results'] = results
        submission['graded'] = True
        submission['wrong_questions'] = wrong_questions
        
        self.file_handler.save_submission(submission)
        
        # 保存错题分析
        analysis = {
            'student_name': submission['student_name'],
            'exam_id': submission['exam_id'],
            'submission_id': submission_id,
            'score': final_score,
            'total_questions': total_questions,
            'wrong_questions': wrong_questions,
            'analysis_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        self.file_handler.save_analysis(submission['student_name'], analysis)
        return final_score, results, wrong_questions